<template>
  <div class="tax-report">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>税务数据报送</span>
        </div>
      </template>

      <el-row :gutter="20">


        <el-col :span="8">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>身份信息报送</span>
              </div>
            </template>
            <div class="report-content">
              <p>待报送数据：{{ identityStats.pending || 0 }} 条</p>
              <p>报送成功：{{ identityStats.success || 0 }} 条</p>
              <p>报送失败：{{ identityStats.failed || 0 }} 条</p>
              <el-button type="primary" @click="reportIdentity" :loading="identityLoading">
                开始报送
              </el-button>
            </div>
          </el-card>
        </el-col>

        <el-col :span="8">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>收入信息报送</span>
              </div>
            </template>
            <div class="report-content">
              <p>待报送数据：{{ incomeStats.pending || 0 }} 条</p>
              <p>报送成功：{{ incomeStats.success || 0 }} 条</p>
              <p>报送失败：{{ incomeStats.failed || 0 }} 条</p>
              <el-button type="primary" @click="reportIncome" :loading="incomeLoading">
                开始报送
              </el-button>
            </div>
          </el-card>
        </el-col>


        <el-col :span="8">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>平台信息报送</span>
              </div>
            </template>
            <div class="report-content">
              <div class="report-content">
                <p>待报送数据：{{ platformStats.pending || 0 }} 条</p>
                <p>报送成功：{{ platformStats.success || 0 }} 条</p>
                <p>报送失败：{{ platformStats.failed || 0 }} 条</p>
                <el-button type="primary" @click="reportPlatform" :loading="platformLoading">
                  开始报送
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>

    <!-- 报送结果弹窗 -->
    <el-dialog
        v-model="resultDialogVisible"
        title="报送结果"
        width="600px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
    >
      <div v-if="reportResult">
        <el-result
            :icon="reportResult.totalCount>0 ?'success':'warning'"
            :title="reportResult.message"
        >
          <template #extra>
            <!-- 详细统计信息 -->
            <div class="statistics-details" v-if="reportResult.totalCount>0">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-statistic title="总记录数" :value="reportResult.totalCount || 0"/>
                </el-col>
                <el-col :span="8">
                  <el-statistic title="成功数量" :value="reportResult.successCount || 0" value-style="color: #67c23a"/>
                </el-col>
                <el-col :span="8">
                  <el-statistic title="失败数量" :value="reportResult.failCount || 0" value-style="color: #f56c6c"/>
                </el-col>
              </el-row>
            </div>

            <!-- 错误详情 -->
            <div v-if="reportResult.errorMessages && reportResult.errorMessages.length > 0">
              <el-divider content-position="left">错误详情</el-divider>
              <el-alert
                  v-for="(error, index) in reportResult.errorMessages"
                  :key="index"
                  :title="`错误 ${index + 1}`"
                  :description="error"
                  type="error"
                  show-icon
                  style="margin-bottom: 10px;"
              />
            </div>
          </template>
        </el-result>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button type="danger" @click="closeResultDialogAndRefresh">
            关闭
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import {ElMessage} from 'element-plus'
import {taxReportApi} from "../api";

const incomeStats = ref({})
const identityStats = ref({})
const platformStats = ref({})
const incomeLoading = ref(false)
const identityLoading = ref(false)
const platformLoading = ref(false)
const allLoading = ref(false)
const retryLoading = ref(false)
const reportResult = ref(null)
const resultDialogVisible = ref(false)

const report = ref({
  id: undefined,
  batchCode: undefined
})

const refreshStats = async () => {
  try {
    // 调用后端API获取真实的统计数据
    const response = await taxReportApi.getReportStatus()
    if (response.data.code === 200) {
      const stats = response.data.data
      incomeStats.value = stats.income || {pending: 0, success: 0, failed: 0}
      identityStats.value = stats.identity || {pending: 0, success: 0, failed: 0}
      platformStats.value = stats.platform || {pending: 0, success: 0, failed: 0}
    } else {
      ElMessage.warning('获取统计数据失败，使用默认值')
      // 使用默认值
      incomeStats.value = {pending: 0, success: 0, failed: 0}
      identityStats.value = {pending: 0, success: 0, failed: 0}
      platformStats.value = {pending: 0, success: 0, failed: 0}
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败，使用默认值')
    // 使用默认值
    incomeStats.value = {pending: 0, success: 0, failed: 0}
    identityStats.value = {pending: 0, success: 0, failed: 0}
    platformStats.value = {pending: 0, success: 0, failed: 0}
  }
}

const reportIncome = async () => {
  incomeLoading.value = true
  try {
    const response = await taxReportApi.reportIncomeData(report.value)
    if (response.data.code === 200) {
      // ElMessage.success('收入信息报送完成')
      // 正确处理后端返回的数据结构
      reportResult.value = {
        success: response.data.data.success,
        message: response.data.data.message,
        totalCount: response.data.data.totalCount,
        successCount: response.data.data.successCount,
        failCount: response.data.data.failCount
      }
      refreshStats()
      showResultDialog()
    } else {
      ElMessage.error(response.data.message || '报送失败')
    }
  } catch (error) {
    ElMessage.error('报送失败：' + error.message)
  } finally {
    incomeLoading.value = false
  }
}

const reportIdentity = async () => {
  identityLoading.value = true
  try {
    const response = await taxReportApi.reportIdentityData(report.value)
    if (response.data.code === 200) {
      // ElMessage.success('身份信息报送完成')
      // 正确处理后端返回的数据结构
      reportResult.value = {
        success: response.data.data.success,
        message: response.data.data.message,
        totalCount: response.data.data.totalCount,
        successCount: response.data.data.successCount,
        failCount: response.data.data.failCount
      }
      refreshStats()
      showResultDialog()
    } else {
      ElMessage.error(response.data.message || '报送失败')
    }
  } catch (error) {
    ElMessage.error('报送失败：' + error.message)
  } finally {
    identityLoading.value = false
  }
}

const reportPlatform = async () => {
  platformLoading.value = true
  try {
    const response = await taxReportApi.reportPlatformData(report.value)
    if (response.data.code === 200) {
      // ElMessage.success('平台信息报送完成')
      // 正确处理后端返回的数据结构
      reportResult.value = {
        success: response.data.data.success,
        message: response.data.data.message,
        totalCount: response.data.data.totalCount,
        successCount: response.data.data.successCount,
        failCount: response.data.data.failCount
      }
      refreshStats()
      showResultDialog()
    } else {
      ElMessage.error(response.data.message || '报送失败')
    }
  } catch (error) {
    ElMessage.error('报送失败：' + error.message)
  } finally {
    platformLoading.value = false
  }
}

const reportAll = async () => {
  allLoading.value = true
  try {
    await Promise.all([
      reportIncome(),
      reportIdentity(),
      reportPlatform()
    ])
    ElMessage.success('全部报送完成')
  } catch (error) {
    ElMessage.error('全部报送失败：' + error.message)
  } finally {
    allLoading.value = false
  }
}

const retryFailed = async () => {
  retryLoading.value = true
  try {
    const response = await taxReportApi.retryFailedReport('all')
    if (response.data.code === 200) {
      ElMessage.success('失败重试完成')
      // 正确处理后端返回的数据结构
      reportResult.value = {
        success: response.data.data.success,
        message: response.data.data.message,
        totalCount: response.data.data.totalCount,
        successCount: response.data.data.successCount,
        failCount: response.data.data.failCount,
        errorMessages: response.data.data.errorMessages || []
      }
      refreshStats()
      showResultDialog()
    } else {
      ElMessage.error(response.data.message || '重试失败')
    }
  } catch (error) {
    ElMessage.error('重试失败：' + error.message)
  } finally {
    retryLoading.value = false
  }
}

const showResultDialog = () => {
  console.log('显示结果弹窗，数据：', reportResult.value)
  resultDialogVisible.value = true
}

const closeResultDialog = () => {
  resultDialogVisible.value = false
  reportResult.value = null
}

const closeResultDialogAndRefresh = () => {
  closeResultDialog()
  refreshStats()
}

onMounted(() => {
  refreshStats()
})
</script>

<style scoped>
.tax-report {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.report-content {
  text-align: center;
}

.report-content p {
  margin: 10px 0;
  color: #606266;
}

.el-divider {
  margin: 30px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 弹窗内容样式 */
:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-result__title) {
  font-size: 18px;
  margin-bottom: 10px;
}

:deep(.el-result__subtitle) {
  font-size: 14px;
  color: #606266;
  margin-bottom: 20px;
}

.statistics-details {
  margin: 20px 0;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.statistics-details .el-statistic {
  text-align: center;
}

.statistics-details .el-statistic__title {
  font-size: 14px;
  color: #606266;
}

.statistics-details .el-statistic__number {
  font-size: 24px;
  font-weight: bold;
}
</style>
